const { verify, getToken } = require('../token');
const mongoose = require('mongoose');
const LogModel = mongoose.model('Log');

const logMiddleware = async (ctx, next) => {
  const startTime = Date.now();

  await next();

  let payload = {};
  try {
    payload = await verify(getToken(ctx));
  } catch (error) {
    payload = {
      username: '未知用户',
      id: '',
    };
  }
  const url = ctx.url;
  const method = ctx.method;
  const status = ctx.status;
  let show = url === '/log/delete' ? false : true;

  let resBody = '';
  if (typeof resBody === 'string') {
    resBody = ctx.body;
  } else {
    try {
      resBody = JSON.stringify(ctx.body);
    } catch {
      resBody = '';
    }
  }
  const endTime = Date.now();

  const log = new LogModel({
    user: {
      username: payload.username,
      id: payload._id,
    },
    request: {
      method,
      url,
      body: resBody.toString(),
      status,
    },
    show,
    endTime,
    startTime,
  });
  await log.save();
};

module.exports = {
  logMiddleware,
};
